﻿using System.Data.Entity;
using Isha.Entities;

namespace Isha.Data
{
    public class IshaDbContext : DbContext
    {
        public IshaDbContext()
        {
            
        }

        ~IshaDbContext()
        {
        }

        public virtual void Commit()
        {
            base.SaveChanges();
        }

        public DbSet<User> Users { get; set; }

        public DbSet<Role> Roles { get; set; }

        public DbSet<Language> Languages { get; set; }

        public DbSet<Part> Parts { get; set; }

        public DbSet<ContentItem> ContentItems { get; set; }

        public DbSet<ContentType> ContentTypes { get; set; }
       
        public DbSet<Comment> Comments { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ContentItem>()
                .HasKey(e => e.ContentItemID)
                .HasOptional(e => e.ParentItem)
                .WithMany(e => e.ContentItems)
                .HasForeignKey(e => e.ParentItemID);

            modelBuilder.Entity<Comment>()
                .HasRequired<ContentItem>(p => p.ContentItem)
                .WithMany(p => p.Comments)
                .HasForeignKey(p => p.ContentItemID);

            modelBuilder.Entity<Comment>()
               .HasOptional<Comment>(p => p.ParentItem);                              
                
            modelBuilder.Entity<User>()
                .HasMany(u => u.Roles)
                .WithMany(r => r.Users)
                .Map(m =>
                {
                    m.ToTable("RoleMemberships");
                    m.MapLeftKey("UserName");
                    m.MapRightKey("RoleName");
                });

            base.OnModelCreating(modelBuilder);
        }

    }
}
